"""
投标文件分析服务模块
"""
import logging
import json
from typing import Dict, Any
import requests

from .config import CozeConfig
from .exceptions import WorkflowException, ConfigurationException


class WorkflowResultParser:
    """工作流结果解析器"""

    @staticmethod
    def parse_success_result(run_data: dict) -> dict:
        """解析成功状态的结果"""
        result = {}

        # 解析输出结果
        output = run_data.get('output', '')
        if output:
            try:
                output_data = json.loads(output)
                if 'Output' in output_data:
                    output_content = json.loads(output_data['Output'])
                    result['result'] = {
                        'content_type': output_content.get('content_type'),
                        'data': output_content.get('data'),
                        'type_for_model': output_content.get('type_for_model')
                    }
            except json.JSONDecodeError:
                result['raw_output'] = output

        # 添加使用统计
        usage = run_data.get('usage', {})
        if usage:
            result['usage'] = {
                'token_count': usage.get('token_count', 0),
                'input_count': usage.get('input_count', 0),
                'output_count': usage.get('output_count', 0)
            }

        return result

    @staticmethod
    def parse_failure_result(run_data: dict) -> dict:
        """解析失败状态的结果"""
        return {
            'error_message': run_data.get('error_message', '执行失败'),
            'error_code': run_data.get('error_code', 'UNKNOWN')
        }


class CozeAPIClient:
    """Coze API 客户端"""

    def __init__(self, config: CozeConfig):
        self.config = config
        self.logger = logging.getLogger(f"{__name__}.{self.__class__.__name__}")

    def execute_workflow(self, file_name: str, file_url: str) -> dict:
        """执行工作流"""
        url = f"{self.config.api_base}/v1/workflow/run"
        headers = {
            "Authorization": f"Bearer {self.config.api_token}",
            "Content-Type": "application/json"
        }

        payload = {
            "is_async": True,
            "workflow_id": self.config.workflow_id,
            "parameters": {
                "file_name": file_name,
                "file_url": file_url
            }
        }

        try:
            response = requests.post(url, headers=headers, json=payload, timeout=30)
            response.raise_for_status()
            return response.json()

        except requests.RequestException as e:
            raise WorkflowException(f"HTTP请求失败: {str(e)}")

    def get_workflow_history(self, execute_id: str) -> dict:
        """获取工作流执行历史"""
        url = f"{self.config.api_base}/v1/workflows/{self.config.workflow_id}/run_histories/{execute_id}"
        headers = {
            "Authorization": f"Bearer {self.config.api_token}",
            "Content-Type": "application/json"
        }

        try:
            response = requests.get(url, headers=headers, timeout=30)
            response.raise_for_status()
            return response.json()

        except requests.RequestException as e:
            raise WorkflowException(f"HTTP请求失败: {str(e)}")


class BidAnalysisService:
    """投标文件分析服务类 - 重构版"""

    def __init__(self, config: CozeConfig):
        self.config = config
        self.api_client = CozeAPIClient(config)
        self.result_parser = WorkflowResultParser()
        self.logger = logging.getLogger(f"{__name__}.{self.__class__.__name__}")

    def _validate_config(self) -> None:
        """验证配置是否完整"""
        if not self.config.is_valid:
            raise ConfigurationException("Coze配置不完整，请检查配置")

    async def execute_workflow(self, file_name: str, file_url: str) -> Dict[str, Any]:
        """
        执行Coze工作流进行投标文件分析

        Args:
            file_name: 文件名
            file_url: 文件URL

        Returns:
            Dict[str, Any]: 执行结果
        """
        try:
            self._validate_config()

            self.logger.info(f"开始执行投标分析工作流，文件名: {file_name}, 文件URL: {file_url}")

            # 调用Coze工作流（异步方式）
            result_data = self.api_client.execute_workflow(file_name, file_url)

            # 验证响应
            if result_data.get('code') != 0:
                return self._build_error_response(f"执行失败: {result_data.get('msg', '未知错误')}")

            # 获取执行结果
            execute_id = result_data.get('execute_id')
            debug_url = result_data.get('debug_url', '')

            if not execute_id:
                return self._build_error_response('未获取到执行ID')

            self.logger.info(f"工作流已启动，执行ID: {execute_id}")

            return self._build_success_response(execute_id, debug_url)

        except Exception as e:
            self.logger.error(f"执行工作流失败: {str(e)}")
            return self._build_error_response(f'执行工作流失败: {str(e)}')

    def _build_success_response(self, execute_id: str, debug_url: str = '') -> dict:
        """构建成功响应"""
        return {
            'success': True,
            'execute_id': execute_id,
            'debug_url': debug_url,
            'message': '投标分析工作流已启动，请使用execute_id查询结果'
        }

    def _build_error_response(self, message: str) -> dict:
        """构建错误响应"""
        return {
            'success': False,
            'message': message
        }

    async def get_workflow_result(self, execute_id: str) -> Dict[str, Any]:
        """
        查询工作流执行结果

        Args:
            execute_id: 执行ID

        Returns:
            Dict[str, Any]: 查询结果
        """
        try:
            self._validate_config()

            self.logger.info(f"查询工作流执行结果，执行ID: {execute_id}")

            # 获取工作流历史
            result_data = self.api_client.get_workflow_history(execute_id)

            # 验证响应
            if result_data.get('code') != 0:
                return self._build_error_response(f"查询失败: {result_data.get('msg', '未知错误')}")

            # 检查数据
            if not result_data.get('data'):
                return self._build_error_response('未找到执行记录')

            # 解析结果
            return self._parse_workflow_result(execute_id, result_data['data'][0])

        except WorkflowException as e:
            self.logger.error(f"工作流查询失败: {str(e)}")
            return self._build_error_response(f'查询工作流结果失败: HTTP请求错误 - {str(e)}')
        except Exception as e:
            self.logger.error(f"查询工作流结果失败: {str(e)}")
            return self._build_error_response(f'查询工作流结果失败: {str(e)}')

    def _parse_workflow_result(self, execute_id: str, run_data: dict) -> dict:
        """解析工作流结果"""
        execute_status = run_data.get('execute_status', 'Unknown')

        # 基础响应数据
        response_data = {
            'success': True,
            'execute_id': execute_id,
            'execute_status': execute_status,
            'create_time': run_data.get('create_time'),
            'update_time': run_data.get('update_time'),
            'debug_url': run_data.get('debug_url', ''),
        }

        # 根据状态解析结果
        if execute_status == 'Success':
            success_result = self.result_parser.parse_success_result(run_data)
            response_data.update(success_result)
        elif execute_status == 'Fail':
            failure_result = self.result_parser.parse_failure_result(run_data)
            response_data.update(failure_result)

        return response_data
